__author__ = 'wangjc'

from appium import webdriver
import os
from Common.BaseUtil import BaseUtil
from DataBase.Sql import QuerySql
import time
from DataBase.RedisOperate import RedisOperate
from contants.Param import Param
import paramiko


class BaseDriver:
    def __init__(self):
        self.shellFlg = ''
        # 判断当前系统，给subprocess方法设置shell参数设置值
        plat = BaseUtil.getPlatform(self)
        if plat == 'windows':
            self.shellFlg = False
        else:
            self.shellFlg = True
        self.port = ''

    def base_driver(self, db, packageEnv, end, env,trans):
        # 从表里获取服务包、环境信息
        packageInfo = QuerySql.queryPackage(self,end,db)
        envInfo = QuerySql.queryEnv(self,env,db)

        # 获得连接的设备列表
        res = self.deviceInfo(trans)
        deviceSel = ''
        # 判断设备是否正在进行自动化测试（改成多个设备同时运行同一端用例）
        for appDevice in res:
            if appDevice[0] != '':
                device = self.deviceUseInfo(appDevice[0], packageInfo,trans)
                if device == '0':
                    continue
                   # return '有设备正在执行'+packageInfo[0][2]+'端用例，请等待执行完毕再重新创建执行任务'
                elif device == '1':
                    deviceSel = appDevice[0]
                    break
                # else:
                #     continue
        if res.__len__() == 0 or deviceSel == '':
            return '没有可用的设备'
        # 从表里获取设备信息
        deviceInfo = QuerySql.queryDevice(self,deviceSel,db)

        # 拼接参数
        if len(deviceInfo) > 0 and len(packageInfo) > 0 and len(envInfo) > 0:
            desired_caps = {'platformName':deviceInfo[0][1],'platformVersion':deviceInfo[0][2],'deviceName':deviceInfo[0][3],'udid':deviceInfo[0][4],
                            'appPackage':packageInfo[0][0],'appActivity':packageInfo[0][1],'noReset':True,'unicodeKeyboard':True,'resetKeyboard':True
                            ,'skipServerInstallation': True, 'skipDeviceInitialization': True,'automationName':'UiAutomator1'}

        else:
            # 退出执行，剩余用例不执行，并关闭数据库连接
            db.close()
            os._exit(1)
            return '环境信息有误！'

        self.port = RedisOperate().appiumPort(Param.appiumListKey)
        print(self.port)
        # 在本地发起启动appium命令
        # subprocess.Popen('appium -a ' + envInfo[0][0] + ' -p ' + str(self.port) + ' -U ' + deviceSel + '',shell=self.shellFlg)
        print(envInfo[0][0])
        cmd = 'appium -a ' + envInfo[0][0] + ' -p ' + str(self.port) + ' -U ' + deviceSel + ''
        # 向指定appium服务器发起连接请求
        self.excuteSshNew(cmd,trans)

        time.sleep(6)
        # 启动的端口添加到redis
        RedisOperate().addPortToRedis(self.port,Param.appiumListKey)
        # 保存各端执行中的端口，删除端口时使用
        RedisOperate().addHashToRedis(Param.appiumHashKey,end,self.port)
        driver = webdriver.Remote("http://{0}:{1}/wd/hub".format(envInfo[0][0], self.port), desired_caps)
        driver.implicitly_wait(15)
        return driver


    # 获取连接设备列表
    def deviceInfo(self,trans):
        cmd = 'bash --login -c "adb devices"'
        msg = self.excuteSshNew(cmd, trans).readlines()
        # 执行adb命令并获取输出内容（获取代码所在机器上设备连接信息）
        listRes = []
        for  i in range(len(msg)):
            if i+1 <= len(msg)-2:
                res = list(filter(None,msg[i+1].replace('\r\n', '').replace('\t', '').replace('\n','').split('device')))
                listRes.append(res)
        return listRes

    # 获取设备使用情况
    def deviceUseInfo(self,appDevice,packageInfo,trans):
        flg = '2'
        # 执行adb命令并获取输出内容
        # 获取当前系统
        try:
            # res = subprocess.check_output('adb -s ' + appDevice + ' shell dumpsys activity | grep "SplashActivity"',
            #                               shell=self.shellFlg)
            cmd = 'bash --login -c "adb -s ' + appDevice + ' shell dumpsys activity | grep SplashActivity"'
            cmdRet = self.excuteSshNew(cmd, trans).readlines()
            if len(cmdRet) > 0:
                if cmdRet[0] != '':
                    for pa in packageInfo:
                        if cmdRet[0].__contains__(pa[0]):
                            flg = '0'
                            return flg
            else:
                flg = '1'
                return flg

        except Exception:
            return '1'

        return flg


    # 创建ssh连接到指定appium服务器
    def excuteSshNew(self, cmd, trans):
        # 将sshclient的对象的transport指定为以上的trans
        ssh = paramiko.SSHClient()
        ssh._transport = trans
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        # ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(". ./.bash_profile")
        ssh_stdin, ssh_stdout, ssh_stderr = ssh.exec_command(cmd)
        return ssh_stdout








